﻿using System.Linq;
using Epitech.Krisk.Xna.ScreenManagerLib.ScreenManager;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;

namespace Epitech.Krisk.Xna.ScreenManagerLib.Widget
{
    public class ListView : LayoutEntry
    {
        ContentManager _content;
        Texture2D _arrow;
        int _selected = -1;

        public Color DefaultColor { get; set; }
        public Color SelectedColor { get; set; }

        public ListView(Vector2 pos) : base(pos)
        {
            DefaultColor = Color.White;
            SelectedColor = Color.Yellow;
        }

        public void AddElem(string elem)
        {
            MenuEntries.Add(new MenuEntry(elem));
            MenuEntries.Last().DefaultColor = DefaultColor;
            MenuEntries.Last().SelectedColor = SelectedColor;
            MenuEntries.Last().Selected += OnSelectedElem;
        }

        protected void OnSelectedElem(object sender, PlayerIndexEventArgs e)
        {
            if (_selected != SelectedIndex)
                _selected = SelectedIndex;
            else
                _selected = -1;
        }

        public override void LoadContent(MenuScreen currentScreen)
        {
            if (_content == null)
                _content = new ContentManager(currentScreen.ScreenManager.Game.Services, "Content");
            _arrow = _content.Load<Texture2D>("Game/Right");
            base.LoadContent(currentScreen);
        }


        public string SelectedElem
        {
            get 
            { 
                if (_selected != -1)
                    return MenuEntries[_selected].Text;
                return "";
            }
        }
        

        public override void Draw(GameTime gameTime, GameScreen currentScreen)
        {
            if (_selected != -1)
            {
                SpriteBatch sp = currentScreen.ScreenManager.SpriteBatch;
                Vector2 pos = MenuEntries[_selected].Position;

                pos.X -= _arrow.Width - 6;
                pos.Y += (float)_arrow.Height / 4;
                sp.Draw(_arrow, pos, null, Color.White, 0.0f, Vector2.Zero, 0.5f, SpriteEffects.None, 0.0f);
            }
            base.Draw(gameTime, currentScreen);
        }
    }
}
